<?php

namespace app\webactive\service;

use app\common\cachemodel\AppConfig;
use app\common\cachemodel\Goods;
use app\common\cachemodel\OrdersLib;
use app\common\cachemodel\ZhunleUserAccount;
use app\common\cachemodel\ZhunleUserAccountRecord;
use app\common\lib\Alidayu;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\AppTelLogin;
use app\common\model\User;
use app\zyhsapi\model\ZyhsConfig;
use app\zyhsapi\model\ZyhsSmsLog;
use app\zyhsapi\model\ZyhsTelLogin;
use app\zyhsapi\model\ZyhsUser;
use app\zyhsapi\model\ZyhsUserAccount;
use app\zyhsapi\model\ZyhsUserAccountRecord;
use app\zyhsapi\model\ZyhsUserCoupon;
use app\zyhsapi\service\CacheZyhs;
use think\Cache;
use think\Db;
use think\Exception;
use think\Log;

class AppCoinRecharge
{
    /**
     * 获取手机号验证码
     * @param int $areaCode 手机区号
     * @param string $tel 手机号
     * @param int $appType 1=>准了APP  2=>准有好事APP
     * @return array
     * @throws \RedisException
     */
    public function getCode(int $areaCode, string $tel, int $appType)
    {   // 检查手机号是否正确
        if (!$tel || !Util::telRuleCheck($tel, $areaCode))
        {
            return [
                'success' => false,
                'msg' => '手机号错误',
            ];
        }
        $codeType = 'h5_login';

        $time = time();// 当前时间  有效时间暂定为十分钟 600s
        $expire = 600;
        $ip = request()->ip();
        $telStr = 'h5_isSend:' . $areaCode . '-' . $tel;
        if ($appType === 1)
        {   // 准了APP
            $isSendCode = Cache::get($telStr, false);
            if ($isSendCode)
            {
                return [
                    'success' => false,
                    'msg' => '操作频繁，请稍后再试～',
                ];
            }

            try
            {
                $data = (new AppTelLogin())->where(['tel' => (string)$tel, 'expire_time' => ['>', $time]])->findOrFail()->toArray();
            }
            catch (\Exception $e)
            {
                $data = [];
            }
            // 十分钟内无已有验证码
            if (empty($data))
            {
                $code = random_int(100000, 999999);// 六位验证码

                $expire_time = $time + $expire;
                try
                {
                    Db::table('app_tel_login')->insertGetId([
                        'tel' => "$tel",
                        'create_time' => $time,
                        'expire_time' => $expire_time,
                        'code' => $code,
                    ]);
                }
                catch (\Exception $e)
                {
                    Log::write('获取手机验证码失败：' . $e->getMessage() . PHP_EOL . '失败行数：' . $e->getLine() . PHP_EOL . '错误文件：【' . $e->getFile() . '】');
                    return [
                        'success' => false,
                        'msg' => '发送失败',
                    ];
                }

            } else
            {
                $code = $data['code'];
            }
            $alidayu = (new AppConfig())->configInfo('alidayu');
            if ($areaCode === 1)
            {
                $result = Alidayu::getInstance()->sendSmsUSA($tel, $code, 'abroad_login_code');
            } else
            {
                $result = Alidayu::getInstance()->sendSms($tel, $code, $alidayu['login_code'], $areaCode);
            }
            if (!$result)
            {
                return [
                    'success' => false,
                    'msg' => '发送失败',
                ];
            }
            Cache::set($telStr, 1, 50);
            // 记录短信日志
            model('log')->save([
                'tel' => "$tel",
                'ip' => $ip,
                'create_time' => $time,
                'type' => 1,
            ]);

            return [
                'success' => true,
                'msg' => '发送成功',
            ];
        } else
        {   // 准有好事APP
            $isSendCode = CacheZyhs::get($telStr);
            if ($isSendCode)
            {
                return [
                    'success' => false,
                    'msg' => '操作频繁，请稍后再试～',
                ];
            }

            try
            {
                $data = (new ZyhsTelLogin())->where(['tel' => $tel, 'expire_time' => ['>', $time]])->findOrFail()->toArray();
            }
            catch (\Exception $e)
            {
                $data = [];
            }
            // 十分钟内无已有验证码
            if (empty($data))
            {
                $code = random_int(100000, 999999);// 六位验证码

                $expire_time = $time + $expire;
                try
                {
                    Db::table('good_wechat.zyhs_tel_login')->insertGetId([
                        'tel' => "$tel",
                        'create_time' => $time,
                        'expire_time' => $expire_time,
                        'code' => $code,
                    ]);
                }
                catch (\Exception $e)
                {
                    Log::write('获取手机验证码失败：' . $e->getMessage() . PHP_EOL . '失败行数：' . $e->getLine() . PHP_EOL . '错误文件：【' . $e->getFile() . '】');
                    return [
                        'success' => false,
                        'msg' => '发送失败',
                    ];
                }

            } else
            {
                $code = $data['code'];
            }
            $alidayu = (new ZyhsConfig())->configInfo('alidayu');

            $result = Alidayu::getInstance()->sendSmsZyhs($tel, $code, $alidayu['login_code'], $areaCode, $codeType);
            if (!$result)
            {
                return [
                    'success' => false,
                    'msg' => '发送失败',
                ];
            }
            CacheZyhs::set($telStr, 1, 50);
            // 记录短信日志
            (new ZyhsSmsLog())->save([
                'tel' => "$tel",
                'ip' => $ip,
                'create_time' => $time,
                'type' => 1,
            ]);

            return [
                'success' => true,
                'msg' => '发送成功',
            ];
        }
    }

    /**
     * 手机号 登录
     * @param int $areaCode 手机区号
     * @param string $tel 手机号
     * @param string $code 验证码
     * @param bool $isRegister 是否自动注册   true=>注册  false=>不注册
     * @param int $appType 1=>准了APP  2=>准有好事APP
     * @return array
     * @throws ApiException
     * @throws \RedisException
     */
    public function telLogin(int $areaCode, string $tel, string $code, bool $isRegister, int $appType)
    {   // 检查手机号是否正确
        if (!$tel || !Util::telRuleCheck($tel, $areaCode))
        {
            return [
                'success' => false,
                'status' => 0, // 0=>普通错误信息   1=>账号不存在
                'msg' => '手机号错误',
            ];
        }
        $time = time();
        $ip = request()->ip();
        $mobileTel = $areaCode === 86 ? $tel : $areaCode . '-' . $tel;
        $codeType = 'h5_login';
        if (mb_strlen($code) !== 6)
        {
            return [
                'success' => false,
                'status' => 0, // 0=>普通错误信息   1=>账号不存在
                'msg' => '验证码错误',
            ];
        }
        if ($appType === 1)
        {   // 准了APP
            $appConfig = config('app');
            if (!in_array($tel, $appConfig['mobile'])
                || ($areaCode === 86 && $code != substr($appConfig['code'] * (substr($tel, 3, 6)), 0, 6)))
            {   //苹果和安卓应用商店审核账号，固定验证码为666666
                if (($tel == '13045794520' && $code == '666666') || ($tel == '13261877781' && $code == '666666'))
                {
                } else
                {   //  validate 严格校验
                    $mobileCode = Alidayu::getInstance()->checkSmsIdentify($tel, $areaCode);
                    if ($code != $mobileCode)
                    {
                        return [
                            'success' => false,
                            'status' => 0, // 0=>普通错误信息   1=>账号不存在
                            'msg' => '短信验证码错误',
                        ];
                    }
                }
            }

            try
            {
                $user = (new \app\common\cachemodel\User())
                    ->field('id,forbidden,has_self_recode,password,young_pwd,nickname,uc_id,avatar,token_expire,token,uen,is_login_record')
                    ->where(['tel' => $mobileTel])->findOrFail()->toArray();
            }
            catch (Exception $e)
            {
                $user = [];
            }

            if (!$isRegister && !$user)
            {
                return [
                    'success' => false,
                    'status' => 1, // 0=>普通错误信息   1=>账号不存在
                    'msg' => '账号不存在',
                ];
            }
            // 删除 验证码 缓存    ----------------------------------
            Cache::get($mobileTel);
            $UserModel = new User();
            // 该用户是否正常  forbidden==1 禁止登录
            if ($user && $user['forbidden'] == 0)
            {
                return [
                    'success' => true,
                    'uid' => (int)$user['id'],
                    'msg' => '登录成功',
                ];
            } elseif ($user && $user['forbidden'] == 1)
            {
                return [
                    'success' => false,
                    'status' => 0, // 0=>普通错误信息   1=>账号不存在
                    'msg' => '该账号禁止登录',
                ];
            } //手机号不可注册
            elseif (!$user && !empty($code) && !empty($tel))
            {
                $nickname = preg_replace('/(1[3456789]{1}[0-9])[0-9]{4}([0-9]{4})/i', '$1****$2', $tel);
                $checkResult = Util::registCheckLogoutCD(['tel' => $tel]);
                if (!$checkResult['result'])
                {
                    return [
                        'success' => false,
                        'status' => 0, // 0=>普通错误信息   1=>账号不存在
                        'msg' => $checkResult['msg'],
                    ];
                }
                // 第一次登录 注册数据
                $user['uen'] = substr(md5($time . mt_rand(0, 1000000) . uniqid()), 0, 12);
                $user['nickname'] = $nickname;
                $user['reg_time'] = $time;
                $user['reg_ip'] = $ip;
                $user['last_login'] = $time;
                $user['last_ip'] = $ip;
                $user['last_active'] = $time;
                $user['status'] = 1;
                $user['sex'] = 1;
                $user['tel'] = $areaCode === 86 ? $tel : $areaCode . '-' . $tel; // 国内手机号不拼接国际手机区号
                $user['is_first_login'] = 1;
                $user['uc_id'] = md5($tel . $time);
                $user['token'] = '';
                $user['token_expire'] = 0;
                $user['has_self_recode'] = 0;
                $user['channel'] = 0;
                try
                {
                    $user['id'] = $UserModel->insertGetId($user);
                    Cache::set('user_total_amount_' . $user['id'], 0, 86400);// 消费金额为0
                    // 记录注册日志
                    Util::logRealTimeAnalyzeWrite(1, [
                        'user_uid' => $user['id'],
                        'user_name' => $tel,
                        'user_sex' => 0,
                        'user_reg_type' => 99,// 充值H5
                        'user_ip' => $ip,
                    ]);
                }
                catch (\Exception $e)
                {
                    return [
                        'success' => false,
                        'status' => 0, // 0=>普通错误信息   1=>账号不存在
                        'msg' => '注册失败,请稍后重试',
                    ];
                }
                Util::queuePush('register_package', ['uid' => (int)$user['id']], 0);
            }

            if ($user)
            {
                $id = (int)($user['id']);
                return [
                    'success' => true,
                    'uid' => $id,
                    'msg' => '登录成功',
                ];
            }
        } else
        {   // 准了好事APP
            $appConfig = config('zyhsapp');
            if (!in_array($tel, $appConfig['mobile'])
                || ($areaCode === 86 && $code != substr($appConfig['code'] * (substr($tel, 3, 6)), 0, 6)))
            {
                //苹果和安卓应用商店审核账号，固定验证码为666666
                if (($tel == '13045794520' && $code == '666666') || ($tel == '13261877781' && $code == '666666'))
                {
                } else
                {   //  validate 严格校验
                    $mobileCode = Alidayu::getInstance()->checkSmsIdentifyZyhs($tel, $areaCode, $codeType);
                    if ($code != $mobileCode)
                    {
                        return [
                            'success' => false,
                            'status' => 0, // 0=>普通错误信息   1=>账号不存在
                            'msg' => '短信验证码错误',
                        ];
                    }
                }
            }

            try
            {
                $user = (new ZyhsUser())
                    ->field('id,forbidden,has_self_recode,password,young_pwd,nickname,uc_id,avatar,token_expire,token,uen,is_login_record')
                    ->where(['tel' => $mobileTel])->findOrFail()->toArray();
            }
            catch (\Exception $e)
            {
                $user = [];
            }

            if (!$isRegister && !$user)
            {
                return [
                    'success' => false,
                    'status' => 0, // 0=>普通错误信息   1=>账号不存在
                    'msg' => '账号不存在',
                ];
            }
            // 删除 验证码缓存 ----------------------------------
            CacheZyhs::rm($codeType . ':' . $mobileTel);
            $UserModel = new ZyhsUser();
            // 该用户是否正常  forbidden==1 禁止登录
            if ($user && $user['forbidden'] == 0)
            {
                return [
                    'success' => true,
                    'uid' => (int)$user['id'],
                    'msg' => '登录成功',
                ];
            } elseif ($user && $user['forbidden'] == 1)
            {
                return [
                    'success' => false,
                    'status' => 0, // 0=>普通错误信息   1=>账号不存在
                    'msg' => '该账号禁止登录',
                ];
            } //手机号不可注册
            elseif (!$user && !empty($code) && !empty($tel))
            {
                $nickname = preg_replace('/^([\w-]{3})([\w]*)([0-9]{4}$)/i', '$1****$3', $tel);
                $checkResult = Util::ZyhsRegistCheckLogoutCD(['tel' => $tel]);
                if (!$checkResult['result'])
                {
                    return [
                        'success' => false,
                        'status' => 0, // 0=>普通错误信息   1=>账号不存在
                        'msg' => $checkResult['msg'],
                    ];
                }
                // 第一次登录 注册数据
                $user['uen'] = substr(md5($time . mt_rand(0, 1000000) . uniqid()), 0, 12);
                $user['nickname'] = $nickname;
                $user['reg_time'] = $time;
                $user['reg_ip'] = $ip;
                $user['last_login'] = $time;
                $user['last_ip'] = $ip;
                $user['last_active'] = $time;
                $user['status'] = 1;
                $user['sex'] = 1;
                $user['tel'] = $mobileTel; // 国内手机号不拼接国际手机区号
                $user['is_first_login'] = 1;
                $user['uc_id'] = uuid($tel . microtime());
                $user['token'] = '';
                $user['token_expire'] = 0;
                $user['has_self_recode'] = 0;
                $user['channel'] = 0;
                try
                {
                    $user['id'] = $UserModel->insertGetId($user);
                    (new ZyhsUserCoupon())->regUserSendBenefits($user['id'], true);
                }
                catch (\Exception $e)
                {
                    return [
                        'success' => false,
                        'status' => 0, // 0=>普通错误信息   1=>账号不存在
                        'msg' => '注册失败,请稍后重试',
                    ];
                }
            }

            if ($user)
            {
                $id = (int)($user['id']);
                $UserModel->removeUserCache($id);

                return [
                    'success' => true,
                    'uid' => $id,
                    'msg' => '登录成功',
                ];
            }
        }

        return [
            'success' => false,
            'status' => 0, // 0=>普通错误信息   1=>账号不存在
            'msg' => '登录失败,请稍后重试',
        ];
    }

    /**
     * 获取 首页数据
     * @param int $uid 用户uid
     * @param int $appType 1=>准了APP  2=>准有好事APP
     * @return array
     * @throws ApiException
     */
    public function index(int $uid, int $appType)
    {
        $goodList = [];
        if ($appType === 1)
        {
            $user_coin = (new ZhunleUserAccount())->getUserCoinFromCache($uid);
            $coinNum = (int)($user_coin['balance'] ?? 0);
            $userInfo = (new User())->getUserinfo(['id' => $uid]);
            $uen = $userInfo['uen'] ?? '';
            $nickname = $userInfo['nickname'] ?? '';
            $avatar = $userInfo['avatar'] ?? '';

            //获取商品信息
            $goods = (new Goods())->GoodsTypeInfo(9);
            foreach ($goods as $good)
            {
                $extend = $good['extend'] ? json_decode($good['extend'], true) : [];
                $coin_num = $extend['coin_num'] ?? 0;
                $goodList[] = [
                    'num' => (int)$coin_num,
                    'price' => (string)(int)$good['now_prize'],
                    'gid' => (int)$good['id'],
                ];
            }

            $descList = [
                [
                    'color' => '#00D8D3',
                    'content' => '1.请仔细核对账号是否正确。',
                ], [
                    'color' => '#00D8D3',
                    'content' => '2.充值成功后不可退款，不可提现，请谨慎操作！',
                ], [
                    'color' => '#9FA1AA',
                    'content' => '3.充值成功后，请前往准了APP查看准币余额是否准确。',
                ], [
                    'color' => '#9FA1AA',
                    'content' => '4.准了和准有好事的虚拟币不互通，请核对清楚要充值的平台。',
                ], [
                    'color' => '#9FA1AA',
                    'content' => '5.一直未到账请联系微信：zhunleapp2',
                ],
            ];
        } else
        {
            $zyhsUserAccountModel = new ZyhsUserAccount();
            $user_coin = $zyhsUserAccountModel->getUserCoinFromCache($uid);  // 账户信息
            $coinNum = (int)($user_coin['balance'] ?? 0);// 准币余额
            $userInfo = (new ZyhsUser())->getInfoById($uid);
            $uen = $userInfo['uen'] ?? '';
            $nickname = $userInfo['nickname'] ?? '';
            $avatar = $userInfo['avatar'] ?? '';

            $goods = (new ZyhsUserAccount())->coinGoods(false, $userInfo);
            foreach ($goods as $k => $good)
            {
                $goodList[] = [
                    'num' => $good['coin_num'],
                    'price' => (string)$good['now_prize'],
                    'gid' => (int)$good['id'],
                ];
            }
            $descList = [
                [
                    'color' => '#00D8D3',
                    'content' => '1.请仔细核对账号是否正确',
                ], [
                    'color' => '#00D8D3',
                    'content' => '2.充值成功后不可退款，不可提现，请谨慎操作！',
                ], [
                    'color' => '#5F5F79',
                    'content' => '3.充值成功后，请前往准有好事APP查看准币余额是否准确。',
                ], [
                    'color' => '#5F5F79',
                    'content' => '4.准了和准有好事的虚拟币不互通，请核对清楚要充值的平台。',
                ], [
                    'color' => '#5F5F79',
                    'content' => '5.一直未到账请联系微信：zhunleapp2',
                ],
            ];
        }

        return [
            'nickname' => $nickname,
            'avatar' => $avatar,
            'uen' => $uen,
            'coin' => $coinNum,
            'good_list' => $goodList,
            'desc_list' => $descList,
        ];
    }

    /**
     * 下单
     * @param int $uid 用户uid
     * @param int $tradeType 支付方式 6=>微信JSAPI 8=>微信H5 7=>支付宝手机网页
     * @param int $gid 准币商品id
     * @param int $appType 1=>准了APP  2=>准有好事APP
     * @param string $callback_url 前台支付完成回跳地址
     * @param string $openid 微信支付必传
     * @return array
     * @throws ApiException
     * @throws \Exception
     */
    public function saveOrder(int $uid, int $tradeType, int $gid, int $appType, string $callback_url = '', string $openid = '')
    {
        if ($appType === 1)
        {
            $goods = (new Goods())->GoodsTypeInfo(9);
            $goods = array_column($goods, null, 'id')[$gid] ?? [];
            if (!$goods)
            {
                return [
                    'status' => false,
                    'message' => '未知的商品',
                ];
            }
            $extend = $goods['extend'] ? json_decode($goods['extend'], true) : [];
            $coin_num = $extend['coin_num'] ?? 0;
            //获取订单描述语和订单编号
            $order_type_des = OrdersLib::createOrderId(9);
            $account = OrdersLib::getOrderAccountType($order_type_des['order_id'], $tradeType);
            //获取用户余额信息
            $user_coin = OrdersLib::getCoinNum($uid);
            $insertData = [
                'status' => 0,
                'account' => $account['account'],
                'uid' => $uid,
                'consumer_type' => 1,
                'order_type' => 9,
                'gid' => $gid,
                'pray_date' => 0,
                'rid' => 0,
                'total_amount' => $goods['now_prize'],//实际收入
                'pay_price' => $goods['now_prize'],//用户支付
                'coin_num' => $coin_num,
                'balance' => $coin_num + $user_coin,
                'order_id' => $order_type_des['order_id'],
                'trade_type' => $tradeType,
                'create_time' => time(),
                'extend' => json_encode(['channel_type' => 1], JSON_UNESCAPED_UNICODE),
                'transaction_id' => '',
            ];
            //增加准币明细记录
            $oid = (new ZhunleUserAccountRecord())->SaveData($uid, $insertData);
            if ($oid)
            {
                //支付订单
                $arr = OrdersLib::unifyPayOrder([
                    'oid' => $oid,
                    'trade_type' => $tradeType,
                    'total_amount' => $goods['now_prize'],
                    'pay_des' => $order_type_des['pay_des'],
                    'order_id' => $order_type_des['order_id'],
                    'openid' => $openid,
                    'callback_url' => $callback_url,
                    'order_type' => 9,
                ], 1);
                return [
                    'status' => true,
                    'data' => $arr,
                ];
            }
        } else
        {
            $goods = (new ZyhsUserAccount())->coinGoods(false, ['tel' => ''])[$gid] ?? [];
            if (!$goods)
            {
                return [
                    'status' => false,
                    'message' => '未知的商品',
                ];
            }
            //获取订单描述语和订单编号
            $order_type_des = \app\zyhsapi\lib\OrdersLib::createOrderId(9);
            $account = \app\zyhsapi\lib\OrdersLib::getOrderAccountType($order_type_des['order_id'], $tradeType);
            //获取用户余额信息
            $user_coin = \app\zyhsapi\lib\OrdersLib::getCoinNum($uid);
            $insertData = [
                'status' => 0,
                'account' => $account['account'],
                'uid' => $uid,
                'consumer_type' => 1,
                'order_type' => 9,
                'gid' => $gid,
                'total_amount' => $goods['received_price'] ?? $goods['now_prize'],//实际收入
                'pay_price' => $goods['now_prize'],//用户支付
                'coin_num' => $goods['coin_num'],
                'balance' => $goods['coin_num'] + $user_coin,
                'order_id' => $order_type_des['order_id'],
                'trade_type' => $tradeType,
                'create_time' => time(),
                'extend' => json_encode(['channel_type' => 1], JSON_UNESCAPED_UNICODE),
                'transaction_id' => '',
            ];
            //增加准币明细记录
            $oid = (new ZyhsUserAccountRecord())->SaveData($uid, $insertData);
            if ($oid)
            {
                //支付订单
                $arr = \app\zyhsapi\lib\OrdersLib::unifyPayOrder([
                    'trade_type' => $tradeType,
                    'total_amount' => $goods['now_prize'],
                    'pay_des' => $order_type_des['pay_des'],
                    'order_id' => $order_type_des['order_id'],
                    'openid' => $openid,
                    'callback_url' => $callback_url,
                    'order_type' => 9,
                ], 1);
                return [
                    'status' => true,
                    'data' => $arr,
                ];
            }
        }
        return [
            'status' => false,
            'message' => '下单失败',
        ];
    }
}
